<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书馆管理系统 - 借阅管理</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="auth.js"></script>
    <script src="permission-control.js"></script>
</head>
<body>
    <!-- 主系统页面 -->
    <div id="mainPage" class="page active">
        <!-- 顶部导航栏 -->
        <header class="header">
            <div class="header-left">
                <button class="sidebar-toggle" onclick="toggleSidebar()">
                    <i class="fas fa-bars"></i>
                </button>
                <h1 class="logo">
                    <i class="fas fa-book"></i>
                    图书馆管理系统
                </h1>
            </div>
            <div class="header-right">
                <div class="notification-icon" onclick="showNotifications()">
                    <i class="fas fa-bell"></i>
                    <span class="notification-badge" id="notificationBadge">0</span>
                </div>
                <div class="user-menu">
                    <span class="user-name" id="currentUserName">管理员</span>
                    <div class="user-dropdown">
                        <button class="dropdown-btn">
                            <i class="fas fa-user-circle"></i>
                            <i class="fas fa-chevron-down"></i>
                        </button>
                        <div class="dropdown-content">
                            <a href="#" onclick="showProfile()">个人资料</a>
                            <a href="#" onclick="changePassword()">修改密码</a>
                            <a href="#" onclick="logout()">退出登录</a>
                        </div>
                    </div>
                </div>
            </div>
        </header>

        <!-- 侧边栏 -->
        <aside class="sidebar" id="sidebar">
            <nav class="sidebar-nav">
                <ul id="sidebarMenu">
                    <!-- 菜单将通过JavaScript动态生成 -->
                </ul>
            </nav>
        </aside>

        <!-- 主内容区域 -->
        <main class="main-content">
            <!-- 借阅管理页面 -->
            <div id="borrows" class="content-page active">
                <div class="page-header">
                    <h2>借阅管理</h2>
                    <div class="header-actions">
                        <button class="btn btn-primary" onclick="showBorrowModal()">
                            <i class="fas fa-plus"></i>
                            借阅图书
                        </button>
                        <button class="btn btn-success" onclick="showReturnModal()">
                            <i class="fas fa-undo"></i>
                            归还图书
                        </button>
                        <button class="btn btn-warning" onclick="showRenewModal()">
                            <i class="fas fa-redo"></i>
                            续借图书
                        </button>
                    </div>
                </div>
                <div class="page-filters">
                    <div class="filter-group">
                        <input type="text" id="borrowSearch" placeholder="搜索借阅记录..." class="form-control">
                        <select id="borrowStatusFilter" class="form-control">
                            <option value="">所有状态</option>
                            <option value="borrowing">借阅中</option>
                            <option value="returned">已归还</option>
                            <option value="overdue">逾期</option>
                            <option value="lost">丢失</option>
                        </select>
                        <button class="btn btn-secondary" onclick="searchBorrows()">
                            <i class="fas fa-search"></i>
                            搜索
                        </button>
                    </div>
                </div>
                <div class="table-container">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>用户</th>
                                <th>图书</th>
                                <th>借阅时间</th>
                                <th>应还时间</th>
                                <th>实际归还时间</th>
                                <th>续借次数</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="borrowTableBody">
                        </tbody>
                    </table>
                </div>
                <div class="pagination" id="borrowPagination">
                </div>
                <div class="pagination-tools" id="borrowPaginationTools"></div>
            </div>
        </main>
    </div>

    <!-- 模态框 -->
    <div id="modalOverlay" class="modal-overlay">
        <div class="modal">
            <div class="modal-header">
                <h3 id="modalTitle">标题</h3>
                <button class="modal-close" onclick="closeModal()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-body" id="modalBody">
            </div>
            <div class="modal-footer" id="modalFooter">
            </div>
        </div>
    </div>

    <!-- 加载提示 -->
    <div id="loadingOverlay" class="loading-overlay">
        <div class="loading-spinner">
            <i class="fas fa-spinner fa-spin"></i>
            <p>加载中...</p>
        </div>
    </div>

    <!-- 消息提示 -->
    <div id="messageContainer" class="message-container">
    </div>

    <script src="api.js"></script>
    <script>
        // 全局变量
        let currentUser = null;
        let currentPageNum = 1;
        let currentPageSize = 10;

        // 页面初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 延迟初始化以确保所有资源加载完成
            setTimeout(() => {
                initializeApp();
            }, 100);
        });

        // 初始化应用
        async function initializeApp() {
            try {
                // 使用通用权限检查
                if (!initializePagePermission()) {
                    return;
                }
                
                currentUser = authManager.getCurrentUser();
                
                // 生成动态菜单
                generateSidebarMenu();
                
                // 更新用户信息
                document.getElementById('currentUserName').textContent = currentUser.realName || currentUser.username;
                
                // 加载借阅数据
                await loadBorrows();
                
                // 加载未读通知数量
                await loadUnreadNotificationCount();
            } catch (error) {
                console.error('初始化应用失败:', error);
                Utils.showMessage('初始化应用失败', 'error');
            }
        }

        // 检查登录状态
        function checkLoginStatus() {
            const savedUser = localStorage.getItem('currentUser');
            if (savedUser) {
                currentUser = JSON.parse(savedUser);
            }
        }

        // 生成侧边栏菜单
        function generateSidebarMenu() {
            const sidebarMenu = document.getElementById('sidebarMenu');
            if (sidebarMenu) {
                sidebarMenu.innerHTML = authManager.generateSidebarMenu();
            }
        }

        // 切换侧边栏
        function toggleSidebar() {
            const sidebar = document.getElementById('sidebar');
            sidebar.classList.toggle('active');
        }

        // 退出登录
        function logout() {
            currentUser = null;
            localStorage.removeItem('currentUser');
            window.location.href = 'login.html';
            Utils.showMessage('已退出登录', 'info');
        }

        // 显示通知
        function showNotifications() {
            window.location.href = 'notifications.html';
        }

        // 加载通知数量
        async function loadNotificationCount() {
            try {
                const currentUser = JSON.parse(localStorage.getItem('currentUser') || '{}');
                if (currentUser.userId) {
                    const response = await NotificationAPI.getUnreadCount(currentUser.userId);
                    if (response.result === 'SUCCESS') {
                        const count = response.data || 0;
                        const badge = document.getElementById('notificationBadge');
                        if (badge) {
                            badge.textContent = count;
                            badge.style.display = count > 0 ? 'block' : 'none';
                        }
                    }
                }
            } catch (error) {
                console.error('Load notification count error:', error);
            }
        }

        // 显示个人资料
        function showProfile() {
            Utils.showMessage('个人资料功能开发中', 'info');
        }

        // 修改密码
        function changePassword() {
            Utils.showMessage('修改密码功能开发中', 'info');
        }

        // 加载未读通知数量
        async function loadUnreadNotificationCount() {
            try {
                const response = await NotificationAPI.countUnreadNotifications(currentUser.userId);
                if (response.result === 'SUCCESS') {
                    const badge = document.getElementById('notificationBadge');
                    if (badge) {
                        badge.textContent = response.data || 0;
                        badge.style.display = response.data > 0 ? 'block' : 'none';
                    }
                }
            } catch (error) {
                console.error('Load unread notification count error:', error);
            }
        }

        // 加载借阅数据
        async function loadBorrows(page = 1) {
            try {
                Utils.showLoading();
                
                const keyword = document.getElementById('borrowSearch')?.value || '';
                let status = document.getElementById('borrowStatusFilter')?.value || '';
                
                // 将字符串状态转换为后端可识别的枚举码，避免解析错误
                if (status) {
                    const map = { borrowing: 1, returned: 2, overdue: 3, lost: 4 };
                    status = map[status] !== undefined ? map[status].toString() : status;
                } else {
                    // 默认显示所有状态的借阅记录，包括已归还的
                    status = '';
                }
                
                const response = await BorrowAPI.pageBorrows(page, currentPageSize, '', status, keyword);
                
                if (response.result === 'SUCCESS') {
                    renderBorrowTable(response.data.records);
                    renderPagination('borrowPagination', page, response.data.pages, loadBorrows);
                    // 工具栏：跳页 + 每页条数
                    renderPaginationTools('borrowPaginationTools', response.data.pages,
                        (n) => { currentPageNum = n; loadBorrows(n); },
                        (size) => { currentPageSize = size; currentPageNum = 1; loadBorrows(1); }
                    );
                } else {
                    Utils.showMessage(response.message || '加载借阅数据失败', 'error');
                }
            } catch (error) {
                Utils.showMessage('加载借阅数据失败', 'error');
                console.error('Borrows load error:', error);
            } finally {
                Utils.hideLoading();
            }
        }

        // 渲染借阅表格
        function renderBorrowTable(borrows) {
            const tbody = document.getElementById('borrowTableBody');
            if (!tbody) return;
            
            if (!borrows || borrows.length === 0) {
                tbody.innerHTML = '<tr><td colspan="9" style="text-align: center;">暂无借阅记录</td></tr>';
                return;
            }
            
            try {
                tbody.innerHTML = borrows.map(borrow => `
                    <tr>
                        <td>${borrow.borrowId || ''}</td>
                        <td>${borrow.userName || borrow.username || ''}</td>
                        <td>${borrow.bookName || ''}</td>
                        <td>${borrow.borrowDate || borrow.borrowTime ? Utils.formatDate(borrow.borrowDate || borrow.borrowTime) : ''}</td>
                        <td>${borrow.dueDate || borrow.dueTime ? Utils.formatDate(borrow.dueDate || borrow.dueTime) : ''}</td>
                        <td>${borrow.returnDate || borrow.returnTime ? Utils.formatDate(borrow.returnDate || borrow.returnTime) : '-'}</td>
                        <td>${borrow.renewCount || 0}</td>
                        <td><span class="status-badge status-${borrow.status || 'borrowing'}">${Utils.getStatusText(borrow.status) || '未知'}</span></td>
                        <td>
                            <div class="btn-group-table">
                                ${borrow.status === 'borrowing' ? `
                                    <button class="btn btn-sm btn-success" onclick="returnBook(${borrow.borrowId})">
                                        <i class="fas fa-undo"></i> <span>归还</span>
                                    </button>
                                    <button class="btn btn-sm btn-warning" onclick="showRenewModal(${borrow.borrowId})">
                                        <i class="fas fa-redo"></i> <span>续借</span>
                                    </button>
                                    <button class="btn btn-sm btn-overdue" onclick="markAsOverdue(${borrow.borrowId})">
                                        <i class="fas fa-clock"></i> <span>逾期</span>
                                    </button>
                                    <button class="btn btn-sm btn-lost" onclick="markAsLost(${borrow.borrowId})">
                                        <i class="fas fa-book-dead"></i> <span>丢失</span>
                                    </button>
                                ` : ''}
                                ${borrow.status === 'overdue' ? `
                                    <button class="btn btn-sm btn-success" onclick="returnBook(${borrow.borrowId})">
                                        <i class="fas fa-undo"></i> <span>归还</span>
                                    </button>
                                    <button class="btn btn-sm btn-lost" onclick="markAsLost(${borrow.borrowId})">
                                        <i class="fas fa-book-dead"></i> <span>丢失</span>
                                    </button>
                                ` : ''}
                                ${borrow.status === 'lost' ? `
                                    <button class="btn btn-sm btn-primary" onclick="showPayFineModal(${borrow.borrowId})">
                                        <i class="fas fa-money-bill-wave"></i> <span>支付赔偿</span>
                                    </button>
                                ` : ''}
                                <button class="btn btn-sm btn-info" onclick="viewBorrowDetail(${borrow.borrowId})">
                                    <i class="fas fa-eye"></i> <span>详情</span>
                                </button>
                            </div>
                        </td>
                    </tr>
                `).join('');
            } catch (error) {
                console.error('渲染借阅表格失败:', error);
                tbody.innerHTML = '<tr><td colspan="9" style="text-align: center;">数据渲染失败</td></tr>';
            }
        }

        // 搜索借阅记录
        function searchBorrows() {
            currentPageNum = 1;
            loadBorrows(1);
        }

        // 显示借阅图书模态框
        function showBorrowModal() {
            showModal('借阅图书', `
                <form id="borrowForm">
                    <div class="form-group">
                        <label for="borrowUserId">用户</label>
                        <select id="borrowUserId" name="userId" required>
                            <option value="">请选择用户</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="borrowBookId">图书</label>
                        <select id="borrowBookId" name="bookId" required>
                            <option value="">请选择图书</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="borrowItemId">图书条目</label>
                        <select id="borrowItemId" name="itemId" required>
                            <option value="">请先选择图书</option>
                        </select>
                    </div>
                </form>
            `, `
                <button class="btn btn-primary" onclick="submitBorrow()">借阅</button>
                <button class="btn btn-secondary" onclick="closeModal()">取消</button>
            `);
            
            // 加载用户和图书数据
            loadUsersForBorrow();
            loadBooksForBorrow();
            
            // 添加图书选择事件监听器
            setTimeout(() => {
                const bookSelect = document.getElementById('borrowBookId');
                if (bookSelect) {
                    bookSelect.addEventListener('change', function() {
                        const bookId = this.value;
                        if (bookId) {
                            loadBookItems(bookId);
                        } else {
                            const itemSelect = document.getElementById('borrowItemId');
                            itemSelect.innerHTML = '<option value="">请先选择图书</option>';
                        }
                    });
                }
            }, 100);
        }

        // 加载图书条目
        async function loadBookItems(bookId) {
            try {
                const response = await BookItemAPI.getAvailableBookItems(bookId);
                if (response.result === 'SUCCESS') {
                    const items = response.data;
                    const select = document.getElementById('borrowItemId');
                    if (select) {
                        select.innerHTML = '<option value="">请选择图书条目</option>' +
                            items.map(item => `<option value="${item.itemId}">条目ID: ${item.itemId}</option>`).join('');
                    }
                }
            } catch (error) {
                console.error('Load book items error:', error);
                Utils.showMessage('加载图书条目失败', 'error');
            }
        }

        // 显示归还图书模态框
        function showReturnModal() {
            showModal('归还图书', `
                <form id="returnForm">
                    <div class="form-group">
                        <label for="returnBorrowId">借阅记录ID</label>
                        <input type="number" id="returnBorrowId" name="borrowId" placeholder="请输入借阅记录ID" required>
                    </div>
                </form>
            `, `
                <button class="btn btn-primary" onclick="submitReturn()">归还</button>
                <button class="btn btn-secondary" onclick="closeModal()">取消</button>
            `);
        }

        // 显示续借图书模态框
        function showRenewModal(borrowId) {
            // 如果没有提供borrowId，则显示输入框让用户输入
            let formContent = '';
            if (borrowId && !isNaN(borrowId)) {
                formContent = `
                    <form id="renewForm">
                        <input type="hidden" name="borrowId" value="${borrowId}">
                        <div class="form-group">
                            <label for="renewDays">续借天数</label>
                            <input type="number" id="renewDays" name="days" min="1" max="30" value="15" required>
                            <small>请输入续借天数（1-30天）</small>
                        </div>
                    </form>
                `;
            } else {
                formContent = `
                    <form id="renewForm">
                        <div class="form-group">
                            <label for="renewBorrowId">借阅记录ID</label>
                            <input type="number" id="renewBorrowId" name="borrowId" placeholder="请输入借阅记录ID" required>
                        </div>
                        <div class="form-group">
                            <label for="renewDays">续借天数</label>
                            <input type="number" id="renewDays" name="days" min="1" max="30" value="15" required>
                            <small>请输入续借天数（1-30天）</small>
                        </div>
                    </form>
                `;
            }
            
            showModal('续借图书', formContent, `
                <button class="btn btn-primary" onclick="submitRenew()">确认续借</button>
                <button class="btn btn-secondary" onclick="closeModal()">取消</button>
            `);
        }

        // 显示支付罚款模态框
        function showPayFineModal(borrowId) {
            // 检查borrowId有效性
            if (!borrowId || isNaN(borrowId)) {
                Utils.showMessage('无效的借阅记录ID', 'error');
                return;
            }
            
            showModal('支付赔偿', `
                <form id="payFineForm">
                    <input type="hidden" name="borrowId" value="${borrowId}">
                    <div class="form-group">
                        <label for="fineAmount">赔偿金额</label>
                        <input type="number" id="fineAmount" name="amount" step="0.01" readonly>
                    </div>
                </form>
            `, `
                <button class="btn btn-primary" onclick="submitPayFine(${borrowId})">确认支付</button>
                <button class="btn btn-secondary" onclick="closeModal()">取消</button>
            `);
            
            // 获取罚款金额
            loadFineAmount(borrowId);
        }

        // 加载罚款金额
        async function loadFineAmount(borrowId) {
            try {
                const response = await BorrowAPI.getFineAmount(borrowId);
                if (response.result === 'SUCCESS') {
                    document.getElementById('fineAmount').value = response.data;
                }
            } catch (error) {
                console.error('加载罚款金额失败:', error);
            }
        }

        // 归还图书
        async function returnBook(borrowId) {
            // 检查borrowId有效性
            if (!borrowId || isNaN(borrowId)) {
                Utils.showMessage('请选择一条有效的借阅记录进行归还', 'error');
                return;
            }
            
            try {
                Utils.showLoading();
                const response = await BorrowAPI.returnBook(borrowId);
                
                if (response.result === 'SUCCESS') {
                    Utils.showMessage('归还成功', 'success');
                    loadBorrows();
                    // 重新加载通知数量
                    await loadUnreadNotificationCount();
                } else {
                    Utils.showMessage(response.message || '归还失败', 'error');
                }
            } catch (error) {
                Utils.showMessage('归还失败', 'error');
            } finally {
                Utils.hideLoading();
            }
        }

        // 标记为逾期
        async function markAsOverdue(borrowId) {
            // 检查borrowId有效性
            if (!borrowId || isNaN(borrowId)) {
                Utils.showMessage('无效的借阅记录ID', 'error');
                return;
            }
            
            if (!confirm('确定要将该图书标记为逾期吗？')) return;
            
            try {
                Utils.showLoading();
                const response = await BorrowAPI.markAsOverdue(borrowId);
                
                if (response.result === 'SUCCESS') {
                    Utils.showMessage('已标记为逾期', 'success');
                    loadBorrows();
                    // 重新加载通知数量
                    await loadUnreadNotificationCount();
                } else {
                    Utils.showMessage(response.message || '标记失败', 'error');
                }
            } catch (error) {
                Utils.showMessage('标记失败', 'error');
            } finally {
                Utils.hideLoading();
            }
        }

        // 标记为丢失
        async function markAsLost(borrowId) {
            // 检查borrowId有效性
            if (!borrowId || isNaN(borrowId)) {
                Utils.showMessage('无效的借阅记录ID', 'error');
                return;
            }
            
            if (!confirm('确定要将该图书标记为丢失吗？丢失后需要支付赔偿费用。')) return;
            
            try {
                Utils.showLoading();
                const response = await BorrowAPI.markAsLost(borrowId);
                
                if (response.result === 'SUCCESS') {
                    Utils.showMessage('已标记为丢失，请支付赔偿费用', 'success');
                    loadBorrows();
                    // 重新加载通知数量
                    await loadUnreadNotificationCount();
                } else {
                    Utils.showMessage(response.message || '标记失败', 'error');
                }
            } catch (error) {
                Utils.showMessage('标记失败', 'error');
            } finally {
                Utils.hideLoading();
            }
        }

        // 提交支付罚款
        async function submitPayFine(borrowId) {
            // 检查参数有效性
            if (isNaN(borrowId) || !borrowId) {
                Utils.showMessage('请填写完整的支付信息', 'error');
                return;
            }
            
            try {
                Utils.showLoading();
                const response = await BorrowAPI.payFine(borrowId);
                
                if (response.result === 'SUCCESS') {
                    Utils.showMessage('支付成功', 'success');
                    closeModal();
                    loadBorrows();
                    // 重新加载通知数量
                    await loadUnreadNotificationCount();
                } else {
                    Utils.showMessage(response.message || '支付失败', 'error');
                }
            } catch (error) {
                Utils.showMessage('支付失败', 'error');
            } finally {
                Utils.hideLoading();
            }
        }

        // 查看借阅详情
        async function viewBorrowDetail(recordId) {
            try {
                Utils.showLoading();
                const response = await BorrowAPI.getBorrowById(recordId);
                
                if (response.result === 'SUCCESS') {
                    const borrow = response.data;
                    let fineInfo = '';
                    if (borrow.status === 'lost' || borrow.status === 'overdue') {
                        try {
                            const fineResponse = await BorrowAPI.getFineAmount(recordId);
                            if (fineResponse.result === 'SUCCESS') {
                                fineInfo = `
                                <div class="detail-row">
                                    <label>待付金额:</label>
                                    <span>¥${fineResponse.data.toFixed(2)}</span>
                                </div>`;
                            }
                        } catch (error) {
                            console.error('获取罚款金额失败:', error);
                        }
                    }
                    
                    showModal('借阅详情', `
                        <div class="borrow-detail">
                            <div class="detail-row">
                                <label>借阅ID:</label>
                                <span>${borrow.borrowId}</span>
                            </div>
                            <div class="detail-row">
                                <label>用户:</label>
                                <span>${borrow.userName || borrow.username}</span>
                            </div>
                            <div class="detail-row">
                                <label>图书:</label>
                                <span>${borrow.bookName} - ${borrow.author}</span>
                            </div>
                            <div class="detail-row">
                                <label>借阅时间:</label>
                                <span>${Utils.formatDate(borrow.borrowDate || borrow.borrowTime)}</span>
                            </div>
                            <div class="detail-row">
                                <label>应还时间:</label>
                                <span>${Utils.formatDate(borrow.dueDate || borrow.dueTime)}</span>
                            </div>
                            <div class="detail-row">
                                <label>实际归还时间:</label>
                                <span>${borrow.returnDate || borrow.returnTime ? Utils.formatDate(borrow.returnDate || borrow.returnTime) : '未归还'}</span>
                            </div>
                            <div class="detail-row">
                                <label>续借次数:</label>
                                <span>${borrow.renewCount || 0}</span>
                            </div>
                            <div class="detail-row">
                                <label>状态:</label>
                                <span class="status-badge status-${borrow.status}">${Utils.getStatusText(borrow.status)}</span>
                            </div>
                            ${fineInfo}
                        </div>
                    `, `
                        <button class="btn btn-secondary" onclick="closeModal()">关闭</button>
                    `);
                } else {
                    Utils.showMessage(response.message || '获取借阅详情失败', 'error');
                }
            } catch (error) {
                Utils.showMessage('获取借阅详情失败', 'error');
            } finally {
                Utils.hideLoading();
            }
        }

        // 显示模态框
        function showModal(title, body, footer) {
            document.getElementById('modalTitle').textContent = title;
            document.getElementById('modalBody').innerHTML = body;
            document.getElementById('modalFooter').innerHTML = footer;
            document.getElementById('modalOverlay').classList.add('active');
        }

        // 关闭模态框
        function closeModal() {
            document.getElementById('modalOverlay').classList.remove('active');
        }

        // 渲染分页组件
        function renderPagination(containerId, currentPage, totalPages, onPageChange) {
            const container = document.getElementById(containerId);
            if (!container) return;
            
            if (totalPages <= 1) {
                container.innerHTML = '';
                return;
            }
            
            container.innerHTML = '';
            container.appendChild(Utils.createPagination(currentPage, totalPages, onPageChange));
        }

        // 渲染分页工具栏：跳页与每页条数
        function renderPaginationTools(containerId, totalPages, onJump, onSizeChange) {
            const c = document.getElementById(containerId);
            if (!c) return;
            c.innerHTML = `
                <span>到第</span>
                <input id="${containerId}-jump" type="number" min="1" max="${totalPages}" value="${currentPageNum}" style="width:60px">
                <span>页</span>
                <button id="${containerId}-go" class="btn btn-sm btn-primary">确定</button>
                <span style="margin-left:12px">每页</span>
                <select id="${containerId}-size" style="width:90px">
                    <option ${currentPageSize==10?'selected':''} value="10">10 条/页</option>
                    <option ${currentPageSize==20?'selected':''} value="20">20 条/页</option>
                    <option ${currentPageSize==50?'selected':''} value="50">50 条/页</option>
                    <option ${currentPageSize==100?'selected':''} value="100">100 条/页</option>
                </select>
            `;
            const goBtn = document.getElementById(`${containerId}-go`);
            const jumpInput = document.getElementById(`${containerId}-jump`);
            const sizeSelect = document.getElementById(`${containerId}-size`);
            if (goBtn && jumpInput) {
                goBtn.onclick = () => {
                    const n = parseInt(jumpInput.value || '1', 10);
                    const page = Math.min(Math.max(1, n), totalPages);
                    onJump(page);
                };
            }
            if (sizeSelect) {
                sizeSelect.onchange = () => {
                    const size = parseInt(sizeSelect.value, 10);
                    onSizeChange(size);
                };
            }
        }

        // 提交续借
        async function submitRenew() {
            const form = document.getElementById('renewForm');
            const formData = new FormData(form);
            const borrowId = parseInt(formData.get('borrowId'));
            const days = parseInt(formData.get('days'));
            
            // 检查参数有效性
            if (isNaN(borrowId) || !borrowId) {
                Utils.showMessage('请填写完整的续借信息', 'error');
                return;
            }
            
            // 如果days为NaN，则设置默认值为15天
            let renewDays = days;
            if (isNaN(days) || !days || days <= 0) {
                renewDays = 15;
            }
            
            if (renewDays > 30) {
                Utils.showMessage('续借天数不能超过30天', 'error');
                return;
            }
            
            try {
                Utils.showLoading();
                const response = await BorrowAPI.renewBook(borrowId, renewDays);
                
                if (response.result === 'SUCCESS') {
                    Utils.showMessage('续借成功', 'success');
                    closeModal();
                    loadBorrows();
                } else {
                    Utils.showMessage(response.message || '续借失败', 'error');
                }
            } catch (error) {
                console.error('续借异常:', error);
                Utils.showMessage('续借失败: ' + (error.message || '系统异常，请联系管理员'), 'error');
            } finally {
                Utils.hideLoading();
            }
        }

        // 提交归还
        async function submitReturn() {
            const form = document.getElementById('returnForm');
            const formData = new FormData(form);
            const borrowId = parseInt(formData.get('borrowId'));
            
            // 检查参数有效性
            if (isNaN(borrowId) || !borrowId) {
                Utils.showMessage('请填写完整的归还信息', 'error');
                return;
            }
            
            try {
                Utils.showLoading();
                const response = await BorrowAPI.returnBook(borrowId);
                
                if (response.result === 'SUCCESS') {
                    Utils.showMessage('归还成功', 'success');
                    closeModal();
                    loadBorrows();
                    // 重新加载通知数量
                    await loadUnreadNotificationCount();
                } else {
                    Utils.showMessage(response.message || '归还失败', 'error');
                }
            } catch (error) {
                Utils.showMessage('归还失败', 'error');
            } finally {
                Utils.hideLoading();
            }
        }

        // 提交借阅
        async function submitBorrow() {
            const form = document.getElementById('borrowForm');
            const formData = new FormData(form);
            const userId = parseInt(formData.get('userId'));
            const itemId = parseInt(formData.get('itemId'));
            
            // 检查参数有效性
            if (isNaN(userId) || isNaN(itemId) || !userId || !itemId) {
                Utils.showMessage('请填写完整的借阅信息', 'error');
                return;
            }
            
            try {
                Utils.showLoading();
                const borrowData = { userId, itemId };
                const response = await BorrowAPI.borrowBook(borrowData);
                
                if (response.result === 'SUCCESS') {
                    Utils.showMessage('借阅成功', 'success');
                    closeModal();
                    loadBorrows();
                    // 重新加载图书列表以更新可用数量
                    if (typeof window.refreshBooks === 'function') {
                        window.refreshBooks();
                    }
                    // 重新加载通知数量
                    await loadUnreadNotificationCount();
                } else {
                    Utils.showMessage(response.message || '借阅失败', 'error');
                }
            } catch (error) {
                Utils.showMessage('借阅失败', 'error');
            } finally {
                Utils.hideLoading();
            }
        }

        // 加载用户数据到借阅选择框
        async function loadUsersForBorrow() {
            try {
                const response = await UserAPI.pageUsers(1, 100);
                if (response.result === 'SUCCESS') {
                    const users = response.data.records;
                    const select = document.getElementById('borrowUserId');
                    if (select) {
                        select.innerHTML = '<option value="">请选择用户</option>' +
                            users.map(user => `<option value="${user.userId}">${user.realName} (${user.username})</option>`).join('');
                    }
                }
            } catch (error) {
                console.error('Load users for borrow error:', error);
            }
        }

        // 加载图书数据到借阅选择框
        async function loadBooksForBorrow() {
            try {
                const response = await BookAPI.pageBooks(1, 100);
                if (response.result === 'SUCCESS') {
                    // 过滤掉没有可借阅副本的图书
                    const books = response.data.records.filter(book => book.availableCopies > 0);
                    const select = document.getElementById('borrowBookId');
                    if (select) {
                        select.innerHTML = '<option value="">请选择图书</option>' +
                            books.map(book => `<option value="${book.bookId}">${book.bookName} - ${book.author} (可借: ${book.availableCopies})</option>`).join('');
                    }
                }
            } catch (error) {
                console.error('Load books for borrow error:', error);
            }
        }
    </script>
</body>
</html>
